import { resetRouter } from '@/router'

const state = {
  token: '',
  roles: [],
  userinfo: {}
}

const mutations = {
  SET_TOKEN(state, payload) {
    state.token = payload
  },
  SET_ROLES(state, payload) {
    state.roles = payload
  },
  SET_USERINFO(state, payload) {
    state.userinfo = payload
  }
}

const actions = {
  login({ commit }, payload) {
    return new Promise(resolve => {
      let { token, userinfo } = payload

      commit('SET_TOKEN', token)
      commit('SET_USERINFO', userinfo)
      resolve()
    })
  },

  getRoles({ commit }) {
    return new Promise(resolve => {
      let roles = ['admin']
      commit('SET_ROLES', roles)
      resolve(roles)
    })
  },

  logout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USERINFO', {})

      resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
